package com.auz.datagenerator.publishing.tcpip.client;

import java.awt.FlowLayout;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

import javax.swing.JFrame;

/**
 * Simple client receiving data from the data generating server.
 * @author Aurelien Bonnel
 */
public class PreviewClient extends JFrame {

	private static final long serialVersionUID = 8828638963104739489L;
	private PreviewClient client;
	private ClientPanel panel;

	/**
	 * Main class
	 * @param args - the arguments (all optional) as follow:
	 * 	host - the data generating server location
	 *  port - the port to connect to
	 */
	public static void main(String[] args) {
		try {
			System.out.println(InetAddress.getLocalHost().getHostName());
		} catch (UnknownHostException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		String host = "";
		int port = 50625;
		switch (args.length) {
		case 1:
			host = args[0];
			port = 50625;
			break;
		case 2: 
			host = args[0];
			port = Integer.valueOf(args[1]);
			break;
		default:
			host = "localhost";
			port = 50625;
			break;
		}
		try {
			String c;
			do {
				System.out.println("Look for servers ? [y/n]\n");
				Scanner sc = new Scanner(System.in);
				c = sc.next();
			} while(! c.equalsIgnoreCase("y"));
			System.out.println("Waiting for " + host + "...");
			Socket socket = null;
			while(socket == null) {
				try {
					socket = new Socket(host, port);
				} catch(IOException e) {}
			}

			PreviewClient client = new PreviewClient();

			BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			String msg = in.readLine();
			while(msg != null && ! msg.equals("EXIT")) {
				System.out.println(msg);
				if(! msg.equalsIgnoreCase("registered"))
					client.addValue(Double.valueOf(msg));
				msg = in.readLine();
			}
			System.out.println("Socket closed");
			in.close();
		} catch (UnknownHostException e) {
			System.err.println("Host could not be found: " + host);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Constructor
	 */
	public PreviewClient() {
		super("Client");
		setLayout(new FlowLayout());
		panel = new ClientPanel();
		add(panel);
		
		setSize(400, 400);
		pack();
		setVisible(true);
		panel.run();
	}

	/**
	 * Adds a value to the graph
	 * @param value - value to add to the graph
	 */
	public void addValue(double value) {
		panel.addValue(value);
	}

}
